<template>
  <div class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <SearchFrame
        btnName="添加产品"
        :hasPermi="['logic:product:add']"
        :btnFunc="handleAddOrEdit"
        :model="queryParams"
        :search-func="handleQuery"
        :reset="resetQuery"
      >
        <SearchFrameItem prop="categoryId">
          <el-select v-model="queryParams.categoryId" filterable placeholder="请选择产品分类" style="width: 100%" clearable>
            <el-option v-for="item in cateList" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"> </el-option>
          </el-select>
        </SearchFrameItem>
        <SearchFrameItem prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable />
        </SearchFrameItem>
      </SearchFrame>
    </transition>

    <div shadow="never">
      <!-- <template> -->
      <div class="table-header-btns">
        <!-- <el-button type="warning" plain @click="handleExport">导出</el-button> -->
        <img v-hasPermi="['logic:product:export']" src="@/assets/images/productCategoryExport.png" alt="" @click="handleExport" />
      </div>
      <!-- </template> -->
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" class-name="num" align="left" width="120">
          <template #default="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="left" prop="productName" show-overflow-tooltip />
        <el-table-column label="分类" align="left" prop="categoryName" show-overflow-tooltip />
        <el-table-column label="浏览量" align="left" prop="visitCount" show-overflow-tooltip />
        <el-table-column label="状态" align="left" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="toggleStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="left" prop="createTime" show-overflow-tooltip />
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleAddOrEdit(scope.row)" v-hasPermi="['logic:product:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['logic:product:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
  </div>
</template>

<script setup name="ProductNew" lang="ts">
import { listProduct, delProduct, changeStatus } from '@/api/logic/product';
import { listProductCategory } from '@/api/logic/productCategory';
import { ProductVO, ProductForm } from '@/api/logic/product/types';
import { routeLocationKey } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logic_isactive, logic_product_category } = toRefs<any>(proxy?.useDict('logic_isactive', 'logic_product_category'));

const route = useRoute();
const router = useRouter();

const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const initFormData: ProductForm = {
  categoryId: undefined,
  productName: undefined,
}
const data = reactive({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    productName: undefined,
    params: {
    }
  },
});

// 产品分类
const cateList = ref([])
// 获取产品分类
const getCateList = async() => {
  try {
    const res = await listProductCategory();
    cateList.value = res.rows;
  } catch (e) {
    cateList.value = []
  }
}

const { queryParams, form, rules } = toRefs(data);

/** 查询产品管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProduct(queryParams.value);
  res.rows.forEach(el => el.status = !!(el.isActive))
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageSize = 10;
  handleQuery();
}

/** 新增按钮操作 */
const handleAddOrEdit = (row) => {
  // reset();
  // dialog.visible = true;
  // dialog.title = "添加产品管理";
  router.push({
    path: '/workspace/addOrEditProduct',
    query: {
      productId: row ? row.productId : ''
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _productIds = row?.productId || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品管理编号为"' + _productIds + '"的数据项？').finally(() => loading.value = false);
  await delProduct(_productIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('logic/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

// 修改状态操作
const toggleStatus = async (row) => {
  try {
    const res = await changeStatus({ productId: row.productId, isActive: row.isActive ? 0 : 1 })
    proxy?.$modal.msgSuccess(res.msg);
    getList()
  } catch (e) {
    console.log(e)
  }
}
onMounted(() => {
  getCateList()
  getList();
});
onActivated(() => {
  getCateList()
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-card__header) {
  padding-bottom: 14px!important;
}
.table-header-btns {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  img {
    width: 80px;
    height: 32px;
    &:hover {
      cursor: pointer;
    }
  }
}
</style>
